package servlet;

import util.CookieUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 石小俊
 * 用户在浏览器访问时访问该Servlet
 * 此时判断Cookie中是否存在username与password的数据
 * 如果存在
 * 判断username与password是否正确
 * 如果正确
 * 页面直接跳转到主页main.jsp
 * 如果不正确
 * 页面跳转到登录页面login.jsp,进行登录
 * 如果不存在
 * 页面跳转到登录页面login.jsp,进行登录
 */
@WebServlet("/showMain")
public class ShowMainServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取cookie中的username与password
        String username = CookieUtil.findByName("username", request);
        String password = CookieUtil.findByName("password", request);
        if (StringUtil.isNull(username) || StringUtil.isNull(password)) {
            // 两者有任意一个为空,则进入登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return;
        }
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user ")
                    .append(" where username = ? ")
                    .append(" and password = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            rs = ps.executeQuery();
            if (rs.next()) {
                // 进入该分支,表示查询到对应数据了,则用户名与密码正确
                // 页面直接跳转到主页
                request.getRequestDispatcher("/jsp/main.jsp").forward(request, response);
                return;
            }
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }

    }
}
